# Copyright (c) 2025 SenseTime. All Rights Reserved.
# Author: LazyLLM Team,  https://github.com/LazyAGI/LazyLLM

from flask_login import current_user
from sqlalchemy import desc
from utils.util_database import db
from .model import Notification


class NotificationService:
    """通知服务类：处理通知的 CRUD 操作"""

    @staticmethod
    def create_notification(title, content, user_id=None, type='info', link=None):
        """
        创建通知

        Args:
            title: 通知标题
            content: 通知内容
            user_id: 接收用户ID（默认当前用户）
            type: 通知类型
            link: 关联链接

        Returns:
            Notification: 创建的通知对象
        """
        if not user_id:
            user_id = current_user.id

        notification = Notification(
            user_id=user_id,
            tenant_id=current_user.current_tenant_id,
            title=title,
            content=content,
            type=type,
            link=link
        )

        db.session.add(notification)
        db.session.commit()

        return notification

    @staticmethod
    def get_user_notifications(page=1, per_page=20, unread_only=False):
        """
        获取当前用户的通知列表

        Args:
            page: 页码
            per_page: 每页数量
            unread_only: 是否只获取未读通知

        Returns:
            dict: 包含通知列表和分页信息
        """
        query = Notification.query.filter_by(
            user_id=current_user.id,
            tenant_id=current_user.current_tenant_id
        )

        if unread_only:
            query = query.filter_by(is_read=False)

        query = query.order_by(desc(Notification.created_at))

        pagination = query.paginate(page=page, per_page=per_page, error_out=False)

        return {
            'notifications': [n.to_dict() for n in pagination.items],
            'total': pagination.total,
            'page': page,
            'per_page': per_page,
            'unread_count': Notification.query.filter_by(
                user_id=current_user.id,
                tenant_id=current_user.current_tenant_id,
                is_read=False
            ).count()
        }

    @staticmethod
    def mark_as_read(notification_id):
        """标记通知为已读"""
        notification = Notification.query.filter_by(
            id=notification_id,
            user_id=current_user.id,
            tenant_id=current_user.current_tenant_id
        ).first()

        if not notification:
            raise ValueError("通知不存在")

        notification.is_read = True
        db.session.commit()

        return notification

    @staticmethod
    def mark_all_as_read():
        """标记所有通知为已读"""
        Notification.query.filter_by(
            user_id=current_user.id,
            tenant_id=current_user.current_tenant_id,
            is_read=False
        ).update({'is_read': True})

        db.session.commit()

        return True

    @staticmethod
    def delete_notification(notification_id):
        """删除通知"""
        notification = Notification.query.filter_by(
            id=notification_id,
            user_id=current_user.id,
            tenant_id=current_user.current_tenant_id
        ).first()

        if not notification:
            raise ValueError("通知不存在")

        db.session.delete(notification)
        db.session.commit()

        return True
